package com.aniu.cameramanager;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.admin.DevicePolicyManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.util.Log;

import androidx.annotation.RequiresApi;
import androidx.preference.PreferenceManager;

import com.aniu.cameramanager.model.Alarm;
import com.aniu.cameramanager.util.CalendarUtil;
import com.aniu.cameramanager.util.CameraUtil;
import com.aniu.cameramanager.util.WorkTime;

import java.util.Calendar;

public class AlarmReceiver extends BroadcastReceiver {
    private static final String TAG = AlarmReceiver.class.getSimpleName();

    private int amStartWorkTime, amStopWorkTime, pmStartWorkTime, pmStopWorkTime;

    public AlarmReceiver() {
        super();
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onReceive(Context context, Intent intent) {
        String  action = intent.getAction();

        DevicePolicyManager devicePolicyManager = (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
        ComponentName deviceAdmin = new ComponentName(context, MyDeviceAdminReceiver.class);

        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
        amStartWorkTime = sharedPreferences.getInt(WorkTime.AM_START_WORK_KEY, WorkTime.AM_START_WORK_DEFAULT_TIME);
        amStopWorkTime = sharedPreferences.getInt(WorkTime.AM_STOP_WORK_KEY, WorkTime.AM_STOP_WORK_DEFAULT_TIME);
        pmStartWorkTime = sharedPreferences.getInt(WorkTime.PM_START_WORK_KEY, WorkTime.PM_START_WORK_DEFAULT_TIME);
        pmStopWorkTime = sharedPreferences.getInt(WorkTime.PM_STOP_WORK_KEY, WorkTime.PM_STOP_WORK_DEFAULT_TIME);

        // 处理相机事件，同时设置下一次闹钟
        if (action.equals("android.intent.action.BOOT_COMPLETED")) {
            Log.i(TAG, "监听到重启完成事件, action: " + action);

            // 重启后根据当前时间段禁用/启用相机
            CameraUtil.blockOrUnblockCameraNow(context, amStartWorkTime, amStopWorkTime, pmStartWorkTime, pmStopWorkTime);
        } else if (action.equals("ACTION_BLOCK_CAMERA")) {
            devicePolicyManager.setCameraDisabled(deviceAdmin, true);
            Log.i(TAG, "禁用相机成功, action: " + action);

            // 设置下一次的闹钟
            setCameraAlarm(context, getNextCameraAlarm());
        } else if (action.equals("ACTION_UNBLOCK_CAMERA")) {
            devicePolicyManager.setCameraDisabled(deviceAdmin, false);
            Log.i(TAG, "启用相机成功, action: " + action);

            // 设置下一次的闹钟
            setCameraAlarm(context, getNextCameraAlarm());
        }
    }

    private Alarm getNextCameraAlarm() {
        Calendar calendar = Calendar.getInstance();

        String action = null;
        int timeInMinute = 0;

        // 根据当前时间段判断下个闹钟时间和对应事件
        int workdaySection = WorkTime.getWorkdaySection(calendar, amStartWorkTime, amStopWorkTime, pmStartWorkTime, pmStopWorkTime);
        switch (workdaySection) {
            case WorkTime.AM_REST :
                timeInMinute = amStartWorkTime;
                action = "ACTION_BLOCK_CAMERA";
                break;

            case WorkTime.AM_WORK :
                timeInMinute = amStopWorkTime;
                action = "ACTION_UNBLOCK_CAMERA";
                break;

            case WorkTime.NOON_REST :
                timeInMinute = pmStartWorkTime;
                action = "ACTION_BLOCK_CAMERA";
                break;

            case WorkTime.PM_WORK :
                timeInMinute = pmStopWorkTime;
                action = "ACTION_UNBLOCK_CAMERA";
                break;

            case WorkTime.PM_REST : // 和下面的非工作日的处理逻辑一样

            case WorkTime.NON_WORK_DAY :
                CalendarUtil.getInstance().getNextWorkDay(calendar);
                timeInMinute = amStartWorkTime;
                action = "ACTION_BLOCK_CAMERA";
                break;

            default :
                Log.e(TAG, "获取的时间段不正确：" + workdaySection);
        }

        calendar.set(Calendar.HOUR_OF_DAY, timeInMinute / 60);
        calendar.set(Calendar.MINUTE, timeInMinute % 60);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);

        return new Alarm()
                .setAlarmReceiver(AlarmReceiver.class)
                .setCalendar(calendar)
                .setAction(action);
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void setCameraAlarm(Context context, Alarm alarm) {
        Intent intent = new Intent(context, alarm.getAlarmReceiver());
        intent.setAction(alarm.getAction());
        intent.setFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
        intent.setComponent(new ComponentName("com.aniu.cameramanager","com.aniu.cameramanager.AlarmReceiver"));
        PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 999, intent, 0);
        Calendar calendar = alarm.getCalendar();

        AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), alarmIntent);
        Log.i(TAG, "设置闹钟成功： " + alarm.getCalendar().getTime() + " " + alarm.getAction());
    }
}